package com.loyal.camerax.ui.settings.fragment

import android.media.MediaScannerConnection
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.loyal.camerax.R
import com.loyal.camerax.databinding.AdapterGalleryBinding
import com.loyal.camerax.databinding.FragmentPhotoBinding
import com.loyal.camerax.ui.CameraViewModel
import com.loyal.camerax.utils.MediaStoreFile
import com.loyal.camerax.utils.showImmersive

open class PhotoFragment : Fragment() {

    private var _binding: FragmentPhotoBinding? = null
    private val binding get() = _binding!!
    private var galleryAdapter: MediaPagerAdapter? = null
    private val viewModel: CameraViewModel by activityViewModels()
    private val args: PhotoFragmentArgs by navArgs()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel.updateStatus(223)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        _binding = FragmentPhotoBinding.inflate(inflater, container, false)
        return binding.root
    }

    open fun updateGallery(mediaList: MutableList<MediaStoreFile>) {
        galleryAdapter?.setMediaListAndNotify(mediaList)
        binding.viewPager2.setCurrentItem(args.position, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        galleryAdapter = MediaPagerAdapter()
        binding.viewPager2.apply {
            offscreenPageLimit = 2
            adapter = galleryAdapter
        }

        binding.backButton.setOnClickListener {
            val navigateUp = findNavController().navigateUp()
            Log.e(TAG, "navigateUp: $navigateUp")
            /*val action = PhotoFragmentDirections.backToGallery()
            findNavController().navigate(action)*/
        }

        // Handle delete button press
        binding.deleteButton.setOnClickListener {
            val currentPosition = binding.viewPager2.currentItem
            val imageFile = galleryAdapter?.getItem(currentPosition)
            imageFile?.let {
                val mediaFile = it.file
                AlertDialog.Builder(view.context, android.R.style.Theme_Material_Dialog)
                    .setTitle(getString(R.string.delete_title))
                    .setMessage(getString(R.string.delete_dialog))
                    .setPositiveButton(android.R.string.ok) { _, _ ->
                        mediaFile.delete()

                        // Send relevant broadcast to notify other apps of deletion
                        MediaScannerConnection.scanFile(
                            view.context, arrayOf(mediaFile.absolutePath), null, null
                        )

                        // Notify our view pager
                        galleryAdapter?.remove(currentPosition)

                        val count = galleryAdapter?.itemCount
                        if (0 == count) {
                            findNavController().navigateUp()
                        }
                    }

                    .setNegativeButton(android.R.string.cancel, null)
                    .create().showImmersive()
            }
        }
    }

    private inner class MediaPagerAdapter : RecyclerView.Adapter<MediaPagerAdapter.ViewHolder>() {
        private var mediaList = mutableListOf<MediaStoreFile>()

        private inner class ViewHolder(val binding: AdapterGalleryBinding) :
            RecyclerView.ViewHolder(binding.root)

        override fun getItemCount(): Int {
            return mediaList.size
        }

        fun getItem(position: Int): MediaStoreFile? {
            return mediaList.getOrNull(position)
        }

        fun remove(position: Int) {
            mediaList.removeAt(position)
            notifyItemRemoved(position)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val binding =
                AdapterGalleryBinding.inflate(LayoutInflater.from(parent.context), parent, false)
            return ViewHolder(binding)
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val resource = mediaList[position].file
            holder.binding.root.let {
                Glide.with(it).load(resource).into(it)
            }
        }

        override fun getItemId(position: Int): Long {
            return mediaList[position].id
        }

        fun setMediaListAndNotify(newList: MutableList<MediaStoreFile>) {
            val oldSize = mediaList.size
            mediaList.clear()
            notifyItemRangeRemoved(0, oldSize)
            mediaList.addAll(newList)
            notifyItemRangeChanged(0, newList.size)

            val count = itemCount
            notifyItemRangeChanged(0, count)
        }
    }

    override fun onDestroyView() {
        _binding = null
        super.onDestroyView()
    }

    companion object {
        private const val TAG = "PhotoFragment"
    }
}